package com.petadoption.serverclient.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.petadoption.serverclient.entity.User;
import com.petadoption.serverclient.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtil {

    private static UserMapper staticUserMapper;

    @Resource
    private UserMapper userMapper;

    @PostConstruct
    public void setStaticUserMapper() {
        staticUserMapper = userMapper;
    }

    //生成token
    public static String createToken(Integer userId, String sign) {
        return JWT.create().withAudience(String.valueOf(userId)).withExpiresAt(DateUtil.offsetMinute(new Date(), 30)).sign(Algorithm.HMAC256(sign));
    }

    //获取当前用户登录信息
    public static User getCurrenUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                Integer userId = Integer.valueOf(JWT.decode(token).getAudience().get(0));
                return staticUserMapper.selectById(userId);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

}
